<template>
  <CommonImgTemplate>
    <template #topMenu>
      <el-button type="primary" size="small" @click="openFile">
        选择图片
        <i class="iconfont icon-dakaiwenjianjia"></i>
      </el-button>
    </template>

    <template #topImg>
      <img :src="base64Url" />
    </template>

    <template #bottomMenu>
      <p>识别文本:</p>
      <el-button type="success" size="small" :disabled="!base64Url" @click="useCopy(ocrText)">
        复制文本
        <i class="iconfont icon-fuzhi"></i>
      </el-button>
    </template>

    <template #bottomContent>
      {{ ocrText }}
    </template>
  </CommonImgTemplate>

  <EnvPage />
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { message } from "@/utils/Element";
import { open } from "@tauri-apps/api/dialog";
import { readBinaryFile } from "@tauri-apps/api/fs";
// import { invoke } from "@tauri-apps/api";
import { fileReaderFile, isTauri } from "@/utils";
import useCopy from "@/hook/useCopy";

const selected = ref("");
const base64Url = ref("");
const ocrText = ref("");

const openFile = () => {
  if (isTauri()) {
    tauriOpen();
  } else {
    message.warning("非tauri环境");
  }
};

const tauriOpen = async () => {
  const res = await open({
    title: "请选择图片",
    filters: [
      {
        name: "Image",
        extensions: ["png", "jpeg", "jpg"]
      }
    ]
  });

  if (res === null) {
    console.log("取消选择");
  } else if (typeof res === "string") {
    selected.value = res;
    // 读取为 二进制数据
    const file: Uint8Array = await readBinaryFile(res);
    // 转换为 Blob
    const blob: Blob = new Blob([file.buffer]);
    // 转换为 base64
    const result = await fileReaderFile(blob, "Base64");
    if (typeof result === "string") {
      base64Url.value = result;
      ocrText.value = await window.__TAURI__.invoke("handle_ocr", { fileSrc: res });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/styles/var.scss";

img {
  margin: 0 40px;
  height: 200px;
  object-fit: contain;
}

:deep(.bottom-title) {
  min-width: 80px;
  p {
    font-size: 14px;
    color: rgb(116, 116, 116);
    margin-bottom: 6px;
  }
}

:deep(.bottom-content) {
  box-shadow: $shadow;
  padding: 4px 10px;
}
</style>
